package com.fake_Interviews.controller;

import com.alibaba.fastjson.JSON;
import com.fake_Interviews.Mapper.FeedbackMapper;
import com.fake_Interviews.Mapper.InterviewsMapper;
import com.fake_Interviews.Mapper.LoginMapper;
import com.fake_Interviews.Mapper.PdfMapper;
import com.fake_Interviews.module.Feedback;
import com.fake_Interviews.module.Interviews;
import com.fake_Interviews.module.Login;
import com.fake_Interviews.module.Pdf;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api/interviewer")
public class Interviewer_Controller {
    @Autowired
    LoginMapper loginMapper;

    @Autowired
    InterviewsMapper interviewsMapper;

    @Autowired
    FeedbackMapper feedbackMapper;

    @Autowired
    PdfMapper pdfMapper;

    @RequiresAuthentication
    @RequestMapping
    public Response_Interviewer getInterviewer() {
        Login loginInterviewer = (Login) SecurityUtils.getSubject().getPrincipal();//获取表`Login`里的一行数据(面试官信息）
        String usernameInterviewer = loginInterviewer.getUsername();//获取当前用户（面试官）用户名
        List<Interviews> interviews = interviewsMapper.getInterviewsById(loginInterviewer.getId());//获取表`Interviews`里的一行或很多行数据
        Interviews interview = new Interviews();//获取表`Interviews`里的一行数据(最近的一场面试)
        for (var a : interviews) {
            Long time = a.getInterviewtime().getTime() - (System.currentTimeMillis()-2*60*60*1000);
            if (time > 0) {
                if (interview.getInterviewtime() != null && interview.getInterviewtime().getTime() - System.currentTimeMillis() > time) {
                    interview = a;
                }
                if (interview.getInterviewtime() == null) {
                    interview = a;
                }
            }
        }
//        time<0表示获取的面试场次过期，不会添加到interview里，当所有面试都过期，interview.getJobseekers()就是null
//        为什么interview不是null？
        if (interview.getJobseekers() == null) {
            return new Response_Interviewer("无", "无", null, "无", false, 0);
        }
        Login loginInterviewee = loginMapper.selectByPrimaryKey(interview.getJobseekers());//获取表`Login`里的一行数据(求职者信息）
        String usernameInterviewee = loginInterviewee.getUsername();//获取求职者用户名
        Date interviewTime = interview.getInterviewtime();//获取面试时间
        Boolean status = interview.getStatus();//获取状态\
        Integer interviewId = interview.getId();//获取面试id

        String interviewContent = interview.getInterviewcontent();//获取面试内容
        return new Response_Interviewer(usernameInterviewer, usernameInterviewee, interviewTime, interviewContent, status, interviewId);
    }

    //    返回面试官页面需要的反馈
    @RequiresAuthentication
    @RequestMapping("/drawer")
    public List<List<Object>> getInterviewerFeedback() {
        Login loginInterviewer = (Login) SecurityUtils.getSubject().getPrincipal();//获取表`Login`里的一行数据(面试官信息）
        int id = loginInterviewer.getId();//获取用户（面试官）id
        List<Interviews> interviews = interviewsMapper.getInterviewsById(id);//跟一个面试官相关的、表`Interviews`里的一行或很多行数据
        List<List<Object>> list = new ArrayList<>();
        for (var interview : interviews) {
            int interviewId = interview.getId();//面试id
            Date interviewDate = interview.getInterviewtime();//面试时间
            int intervieweeId = interview.getJobseekers();//面试者id
            Feedback feedback = feedbackMapper.getFeedbackByInterviewsId(interviewId);//通过面试id查询一条反馈表记录
            if (feedback == null) continue;
            String feedbackFromJobSeekers = feedback.getFeedbackfromjobseekers();//根据反馈表记录查询求职者反馈
            Login login = loginMapper.selectByPrimaryKey(intervieweeId);//根据面试者id查询Login的一行数据
            String username = login.getUsername();//从一行login数据查询用户名
            List<Object> list1 = new ArrayList<>();
            list1.add(interviewDate);//面试时间
            list1.add(username);//求职者名字
            list1.add(feedbackFromJobSeekers);//反馈内容
            list.add(list1);
        }
        return list;
    }

    //开始面试
    @RequiresAuthentication
    @PostMapping("/start/status")
    public void setStartStatus(@RequestBody Map<String, Integer> map) {
        int interviewsId = map.get("interviewsId");
        if (interviewsId == 0) {
            return;
        }
        Interviews interviews = interviewsMapper.selectByPrimaryKey(interviewsId);
        interviews.setStatus(true);
        interviewsMapper.updateByPrimaryKey(interviews);
    }

    //结束面试
    @RequiresAuthentication
    @PostMapping("/stop/status")
    public void setStopStatus(@RequestBody Map<String, Integer> map) {
        int interviewsId = map.get("interviewsId");
        Interviews interviews = interviewsMapper.selectByPrimaryKey(interviewsId);
        interviews.setStatus(false);
        interviewsMapper.updateByPrimaryKey(interviews);
    }

    //获取文档
    @RequiresAuthentication
    @GetMapping("/pdf/{id}")
    public Map<String, Object> getPdf(@PathVariable int id) {
        Pdf pdf = pdfMapper.selectByPrimaryKey(id);
        Map<String, Object> map = new HashMap<>();
        byte[] bytes=new byte[1024];
        if (pdf!=null){
            bytes = pdf.getPdf();
            map.put("key", bytes);
        }
        else {
            map.put("key", "error");
        }
//        System.out.println(Arrays.toString(bytes));
//        String str = new String(text, "utf-8");
        return map;
    }

//    @GetMapping("/download")
//    public void download(String name, HttpServletResponse response) throws IOException {
//        FileInputStream fileInputStream = new FileInputStream(new File("" + name));
//        ServletOutputStream outputStream = response.getOutputStream();
//        int len = 0;
//        byte[] bytes = new byte[1024];
//        while (len = fileInputStream.read(bytes) len!= -1) {
//            outputStream.write(bytes, 0, len);
//            outputStream.close();
//            fileInputStream.close();
//        }
//    }

}


